package com.example.springboot_demo.dao;

import com.example.springboot_demo.mappers.BookMapper;
import com.example.springboot_demo.pojo.Book;
import com.example.springboot_demo.pojo.Cart;
import com.example.springboot_demo.pojo.CartData;
import com.example.springboot_demo.pojo.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component("BookDao")
public class BookDao {
    @Autowired
    private BookMapper bookMapper;

    //记录每一次查询的书名
    private String queryName = null;


    //删除图书
    public void deleteBookById(int bookId) {
        bookMapper.deleteBook(bookId);
        bookMapper.dropNoColumn();
        bookMapper.addNoColumn();
    }

    //添加和修改图书
    public void updateBook(Book book) {
        bookMapper.updateBook(book);
    }

    //添加一种类型的图书
    public void addBook(Book book) {
        bookMapper.addBook(book);
    }

    //根据id查询图书
    public Book getBookById(int bookId) {
        Book book = bookMapper.queryBookById(bookId);
        return book;
    }

    //查询所有图书
    public List<Book> getAllBook() {
        List bookList = new ArrayList();
        bookList = bookMapper.getAllBook();
        return bookList;
    }


    //带书名的分页查询
    public Page<Book> queryByBookName(int pageNo, int pageSize, String Name) {
        //把Name保存，后面要进行对Name进行改变
        queryName = Name;

        //将书名变为模糊，方便查询
        Name = '%' + Name + '%';
        List<Book> booklist = new ArrayList<>();

        //该页面下的所有数据
        int pageTotal = 0;

        //对name进行分情况，一：name为空， 二：name不为空
        if (queryName == "") pageTotal = bookMapper.getCount();
        else pageTotal = bookMapper.getCountByName(Name);

        //分页查询的索引
        int index = (pageNo - 1) * pageSize;
        queryName = '%' + queryName + '%';

        //进行查询返回结果
        booklist = bookMapper.getBooksByPage(queryName, index, pageSize);

        Page<Book> page = new Page(pageNo, pageTotal, pageTotal % pageSize == 0 ? pageTotal / pageSize : pageTotal / pageSize + 1, booklist, pageSize, queryName);
        return page;
    }


    //带书名查询所有图书
    public List<Book> getAllBooksByName(String queryName) {
        //将书名变为模糊，方便查询
        queryName = '%' + queryName + '%';
        List<Book> booklist = new ArrayList<>();

        //进行查询返回结果
        booklist = bookMapper.getAllBooksByName(queryName);

        return booklist;
    }

    public void updateDataByCart(Cart<Book> cart) {
        Map map = cart.getItems();
        Iterator<Map.Entry<Integer, CartData>> iterator = map.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<Integer, CartData> entry = iterator.next();
            int key = entry.getKey();
            CartData value = entry.getValue();
            bookMapper.updateDataByCart(key, bookMapper.getStock(key)-value.getBookCnt());
        }
    }
}
